<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>基本资料</span>
        <div class="edit-button-container">
          <el-button type="primary" @click="toggleEdit" v-if="!isEditing">修改</el-button>
          <el-button type="primary" @click="updateUser" v-if="isEditing">提交修改</el-button>
          <el-button type="primary" @click="endEdit" v-if="isEditing">取消</el-button>
        </div>
      </div>
    </template>
<!--    基本信息-->
    <div class="user-info-container">
      <el-image
          :src="userInfo.userPic || defaultImage "
          fit="cover"
          class="user-avatar">
        <template #error>
          <div class="image-error">封面加载失败</div>
        </template>
      </el-image>
      <el-row v-if="!isEditing">
        <el-col :span="12">
          <div class="info-item">
            <span class="label">登录名称：</span>
            <span>{{ userInfo.username }}</span>
          </div>
          <div class="info-item">
            <span class="label">用户昵称：</span>
            <span>{{ userInfo.nickname }}</span>
          </div>
          <div class="info-item">
            <span class="label">用户邮箱：</span>
            <span>{{ userInfo.email }}</span>
          </div>
          <div class="info-item">
            <span class="label">用户电话：</span>
            <span>{{ userInfo.phone }}</span>
          </div>
        </el-col>
      </el-row>
      <el-row v-else>
        <el-col :span="12">
          <el-form :model="userInfo" :rules="rules" label-width="100px" size="large">
            <el-form-item label="登录名称">
              <el-input v-model="userInfo.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="用户昵称" prop="nickname">
              <el-input v-model="userInfo.nickname"></el-input>
            </el-form-item>
            <el-form-item label="用户邮箱" prop="email">
              <el-input v-model="userInfo.email"></el-input>
            </el-form-item>
            <el-form-item label="用户电话" prop="email">
              <el-input v-model="userInfo.phone"></el-input>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>

    <!--    预约信息-->
    <div>
      <h2 >预约信息</h2> <!-- 添加的标题 -->
      <el-row>
        <!-- 表格内容 -->
        <el-table :data="ListData" style="width: 100% ;margin-top: 30px;" v-loading="loading">
          <el-table-column label="序号" width="70" type="index" />
          <el-table-column label="头像" prop="userCusPic" width="100px">
            <template #default="{ row }">
              <el-image
                  style="width: 60px; height: 60px; border-radius: 50%;"
                  :src="row.userCusPic"
                  v-if="row.userCusPic"
                  fit="cover"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <span v-else>无头像</span>
            </template>
          </el-table-column>

          <el-table-column label="昵称" prop="customerName" />
          <el-table-column label="中介电话" prop="intTel" />
          <el-table-column label="预约时间" prop="appointmentTime" />
          <el-table-column label="房源地址" prop="address" />
          <el-table-column label="小区名称" prop="communityName" />
          <el-table-column label="房源类型">
            <template #default="{ row }">
              <el-tag
                  :type="{
              0: 'info',
              1:'success'
            }[row.type]"
              >
                {{
                  {
                    "0": '卖房',
                    "1": '租房',
                  }[row.type]
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="预约状态">
            <template #default="{ row }">
              <el-tag
                  :type="{
              0: 'warning',
              1:'success',
              2: 'info',
              3: ''
            }[row.status]"
              >
                {{
                  {
                    0: '待确认',
                    1: '已确认',
                    2: '已取消',
                    3: '已完成'
                  }[row.status]
                }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="240">
            <template #default="{ row }">
              <el-button
                  type="danger"
                  :icon="Close"
                  circle
                  plain
                  @click="handleCancel(row)"
              ></el-button>
            </template>
          </el-table-column>


          <template #empty>
            <el-empty description="暂无用户数据" />
          </template>
        </el-table>

        <!-- 分页条 -->
        <el-pagination
            v-model:current-page="pageNum2"
            v-model:page-size="pageSize2"
            :page-sizes="[3, 5, 10, 15]"
            layout="jumper, total, sizes, prev, pager, next"
            background
            :total="total2"
            @size-change="onSizeChange2"
            @current-change="onCurrentChange2"
            style="margin-top: 20px; justify-content: flex-end"
        />


      </el-row>

    </div>

    <!--   合同信息-->
    <div>
      <h2 >合同信息</h2> <!-- 添加的标题 -->
      <el-row>
        <!-- 表格内容 -->
        <el-table :data="contractListData" style="width: 100% ;margin-top: 30px;" v-loading="loading">
          <el-table-column label="序号" width="70" type="index" />
          <el-table-column label="客户昵称" prop="username" />
          <el-table-column label="房东昵称" prop="landlordname" />
          <el-table-column label="签约时间" prop="createTime" />
          <el-table-column label="到期时间" prop="endTime" />
          <el-table-column label="服务费" prop="intAmount" />
          <el-table-column label="房源费用" prop="houseAmount" />
          <el-table-column label="房源类型">
            <template #default="{ row }">
              <el-tag
                  :type="{
              0: 'info',
              1:'success'
            }[row.type]"
              >
                {{
                  {
                    "0": '卖房',
                    "1": '租房',
                  }[row.type]
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="预约状态">
            <template #default="{ row }">
              <el-tag
                  :type="{
              0: 'warning',
              1:'success',
              2: 'info'
            }[row.status]"
              >
                {{
                  {
                    0: '未支付',
                    1: '已生效',
                    2: '已失效'
                  }[row.status]
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="合同信息" prop="content">
            <template #default="{ row }">
              <el-button
                  v-if="row.content"
                  type="primary"
                  link
                  @click="downloadContract(row.content)"
              >
                下载合同
              </el-button>
              <span v-else>无合同文件</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="240">
            <template #default="{ row }">
              <el-button
                  type="success"
                  :icon="Check"
                  circle
                  plain
                  @click="edithetong(row)"
              ></el-button>
<!--              <el-button-->
<!--                  type="danger"-->
<!--                  :icon="Close"-->
<!--                  circle-->
<!--                  plain-->
<!--                  @click="handleCancelhetong(row)"-->
<!--              ></el-button>-->
            </template>
          </el-table-column>


          <template #empty>
            <el-empty description="暂无用户数据" />
          </template>
        </el-table>

        <!-- 分页条 -->
        <el-pagination
            v-model:current-page="pageNum3"
            v-model:page-size="pageSize3"
            :page-sizes="[3, 5, 10, 15]"
            layout="jumper, total, sizes, prev, pager, next"
            background
            :total="total3"
            @size-change="onSizeChange3"
            @current-change="onCurrentChange3"
            style="margin-top: 20px; justify-content: flex-end"
        />

      </el-row>

    </div>

  </el-card>
</template>

<script setup>
import { ref } from 'vue'
import { updateUserInfo } from "@/api/user.js";
import {ElMessage, ElMessageBox} from "element-plus";
import defaultImage from "@/assets/imgmoren.png";
import {Check, Close} from "@element-plus/icons-vue";
import {addContractService, deleteContractService, getContractPageList, updateContract} from "@/api/contract.js";
import {useTokenStore} from "@/stores/token.js";
import {deleteAppointmentsService, getAppointmentsPageList} from "@/api/appointments.js";
import {addNotice} from "@/api/notice.js";
import { useUserInfoStore } from "@/stores/userinfo.js";
const userInfoStore = useUserInfoStore()
const userinfoId = userInfoStore.info.id;
const tokenStore = useTokenStore();
const housetype = ref(false)
const yuyueVisible = ref(false)
const userInfo = ref({
  ...userInfoStore.info
});
const loading = ref(false);
// 分页条数据模型
const pageNum2 = ref(1) // 当前页
const total2 = ref(0) // 总条数
const pageSize2 = ref(15) // 每页条数
// 分页条数据模型
const pageNum3 = ref(1) // 当前页
const total3 = ref(0) // 总条数
const pageSize3 = ref(15) // 每页条数
// 当每页条数发生了变化，调用此函数
const onSizeChange2 = (size) => {
  pageSize2.value = size
  // 重新获取数据
  ListArray()
}
// 当前页码发生变化，调用此函数
const onCurrentChange2 = (num) => {
  pageNum2.value = num
  // 重新获取数据
  ListArray()
}
// 当每页条数发生了变化，调用此函数
const onSizeChange3 = (size) => {
  pageSize3.value = size
  // 重新获取数据
  contractListArray()
}
// 当前页码发生变化，调用此函数
const onCurrentChange3 = (num) => {
  pageNum3.value = num
  // 重新获取数据
  contractListArray()
}
const handleCancel = (row) => {
  ElMessageBox.confirm('此操作将取消预约申请, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteAppointmentsService(row.id)
    ElMessage.success('预约已取消')
    ListArray()

  }).catch(() => {
    ElMessage.info('取消删除')
  })
}
const downloadContract = (url) => {
  if (!url) {
    ElMessage.error('合同文件不存在');
    return;
  }

  // 如果URL是完整路径直接下载
  if (url.startsWith('http')) {
    window.open(url);
    return;
  }

  // 如果URL是相对路径，拼接基础URL（根据你的实际接口调整）
  const fullUrl = `http://your-api-domain.com${url}`;

  // 使用axios下载（需要处理跨域和认证时）
  axios({
    url: fullUrl,
    method: 'GET',
    responseType: 'blob',
    headers: {
      'Authorization': tokenStore.token // 如果需要认证
    }
  }).then(response => {
    const blob = new Blob([response.data]);
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = url.split('/').pop() || 'contract';
    link.click();
    URL.revokeObjectURL(link.href);
  }).catch(error => {
    ElMessage.error('文件下载失败');
    console.error('下载失败:', error);
  });
}

const searchFormhetong = ref({userId:userinfoId,type:'' })
const searchFormYuyue = ref({ appointmentTime: '',type:'',status:'1',customerId:userinfoId})
const ListData = ref([])
const contractListData = ref([])
const contract = ref({
  createTime:'',
  yuefen:'',
  landlordId:'',
  userId:'',
  houseId:'',
  intermediaryId:'',
  intAmount:'',
  houseAmount:'',
  content:'',
})
const handleCancelhetong = (row) => {
  ElMessageBox.confirm('此操作删除合同, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteContractService(row.id)
    ElMessage.success('删除成功')
    contractListArray()
  }).catch(() => {
    ElMessage.info('取消删除')
  })
}
//知晓合同通知
const edithetong = (row) => {
  ElMessageBox.confirm('确定已知晓合同信息, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await addNotice({
      adminId:userinfoId,
      content:"已知晓合同信息，同意支付",
      id:row.status,
      rolesCustomer:'0',
      rolesIntermediary:'0',
      houseId:row.houseId,
      rolesLandlord:'0',
      userId:row.intermediaryId
    })

    ElMessage.success('通知已发送')
  }).catch(() => {
  })
}

// 获取列表数据
const ListArray = async () => {
  loading.value = true
  const params = {
    ...searchFormYuyue.value,
  };
  try {
    const result = await getAppointmentsPageList(
        pageNum2.value,
        pageSize2.value,
        params
    )
    ListData.value = result.res.items
    total2.value = result.res.total // 确保接口返回total字段
  } finally {
    loading.value = false
  }
}
const contractListArray = async () => {
  loading.value = true
  const params = {
    ...searchFormhetong.value,
  };
  try {
    const result = await getContractPageList(
        pageNum3.value,
        pageSize3.value,
        params
    )
    contractListData.value = result.res.items
    total3.value = result.res.total // 确保接口返回total字段
  } finally {
    loading.value = false
  }
}
const isEditing = ref(false); // 控制是否处于编辑状态

const rules = {
  nickname: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    {
      pattern: /^\S{2,10}$/,
      message: '昵称必须是2-10位的非空字符串',
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入用户邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ]
};

const updateUser = async () => {
  let resul = await updateUserInfo(userInfo.value);
  ElMessage.success('修改成功');
  userInfoStore.setInfo(userInfo.value);
  isEditing.value = false; // 修改成功后回到非编辑状态
};

const toggleEdit = () => {
  isEditing.value = true; // 进入编辑状态
};
const endEdit = () => {
  isEditing.value = false; // 退出编辑状态
};



contractListArray()
ListArray()


</script>

<style scoped>
.page-container {
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.header {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.edit-button-container {
  display: flex;
  align-items: center;
}

.user-info-container {
  text-align: center;
}

.user-avatar {
  width: 150px;
  height: 150px;
  margin: 0 auto 20px;
  border-radius: 50%;
  overflow: hidden;
  border: 4px solid #fff;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.2);
}

.info-item {
  margin-bottom: 10px;
  text-align: left;
  font-size: 16px;
  color: #555;
}

.label {
  font-weight: bold;
  margin-right: 10px;
  color: #333;
}

.el-form {
  margin-top: 20px;
}

.el-button {
  margin-right: 10px;
}
</style>
